package com.zkadmin.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.MouseEvent;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Paging;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysRole;
import com.zkadmin.entity.SysUser;
import com.zkadmin.renderer.UserRoleListRenderer;
import com.zkadmin.service.SysRoleService;
import com.zkadmin.service.SysUserService;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.PagingWrap;

@SuppressWarnings("serial")
public class UserRoleDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysUserService sysUserService;

	@WireVariable
	private SysRoleService sysRoleService;

	private Window win;

	@Wire
	private Listbox roleLst;
	@Wire
	private Paging rolePg;
	@Wire
	private Button createUserRoleBtn;

	private SysUser user;

	@Override
	protected void init(Window win) {
		this.win = win;
		Map<?, ?> args = Executions.getCurrent().getArg();
		if (args != null && !args.isEmpty()) {
			if (args.containsKey("userId")) {
				user = sysUserService.findById((Long) args.get("userId"));
			}
		}
		roleLst.setItemRenderer(new UserRoleListRenderer(user.getRoles()));
		new PagingWrap<SysRole>(sysRoleService, roleLst, rolePg).paging();
		if (user.getId() == 1) {
			createUserRoleBtn.setDisabled(true);
		}
	}

	@Listen("onClick=#cancelBtn,#cancelResourceBtn")
	public void closeDialog(MouseEvent e) {
		win.onClose();
	}

	@Listen("onClick=#createUserRoleBtn")
	public void createUserRole(Event e) {
		List<Listitem> allItems = roleLst.getItems();
		Set<Long> removeRoleIds = new HashSet<Long>();
		for (Listitem listitem : allItems) {
			removeRoleIds.add((Long) listitem.getAttribute("roleId"));
		}

		Set<Long> roleIds = new HashSet<Long>();
		Set<Listitem> selectedItems = roleLst.getSelectedItems();
		for (Listitem listitem : selectedItems) {
			roleIds.add((Long) listitem.getAttribute("roleId"));
		}
		sysUserService.correlationRoles(user.getId(), removeRoleIds, roleIds);
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}
}
